package controller;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.ModelAndView;

import util.DAOException;
import domain.Contact;
import domain.itf.IDAOContact;

/**
 * Controller implementation for delete a {@link Contact}.
 */
@Controller
@RequestMapping("/DeleteContact")
public class DeleteContactController {
	
	@Autowired
    ServletContext servletContext;

	@RequestMapping(method = RequestMethod.GET)
	protected ModelAndView doGet(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("main");
		String memberIdString = request.getParameter("memberId");
		try {
			int memberId = Integer.parseInt(memberIdString);
			
			// get the IDAOContact with spring
			ApplicationContext context = WebApplicationContextUtils
					.getWebApplicationContext(servletContext);
			IDAOContact daoContact = (IDAOContact) context.getBean("DAOContact");
			
			boolean bool = daoContact.deleteContact(memberId);
			if (bool)
				view.addObject("messageInfo", "You have successfully deleted the member.");
			else 
				view.addObject("messageError", "Impossible to delete the member.");
		} catch (NumberFormatException e) {
			view.addObject("messageError", "Impossible to delete the member. The id is not an integer.");
		} catch (DAOException e) {
			view.addObject("messageError", "Impossible to delete the member. " + e.getMessage());
		}
		return view;
	}
}
